<template>
	<div class="app-container">
		<!-- 操作按钮 -->
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
			</el-col>
		</el-row>

		<!-- 数据表格 -->
		<el-table v-loading="loading" :data="carouselList" @selection-change="handleSelectionChange">
			<!-- <el-table-column type="selection" width="55" align="center" /> -->
			<!-- <el-table-column label="ID" align="center" prop="id" /> -->
			<!-- <el-table-column label="标题" align="center" prop="title" /> -->
			<el-table-column label="图片" align="center" prop="url">
				<template slot-scope="scope">
					<el-image style="width: 100px; height: 50px" :src="scope.row.url" :preview-src-list="[scope.row.url]"> </el-image>
				</template>
			</el-table-column>
			<!-- <el-table-column label="跳转链接" align="center" prop="linkUrl" :show-overflow-tooltip="true" /> -->
			<!-- <el-table-column label="排序" align="center" prop="sortOrder" /> -->
			<!-- <el-table-column label="状态" align="center" prop="status">
				<template slot-scope="scope">
					<el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
				</template>
			</el-table-column> -->
			<el-table-column label="创建时间" align="center" prop="createTime" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.createTime) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改轮播图对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="600px" border append-to-body @close="cancel">
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<!-- <el-form-item label="轮播图标题" prop="title">
					<el-input v-model="form.title" placeholder="请输入轮播图标题" />
				</el-form-item>
				<el-form-item label="跳转链接" prop="linkUrl">
					<el-input v-model="form.linkUrl" placeholder="请输入跳转链接" />
				</el-form-item>
				<el-form-item label="排序" prop="sortOrder">
					<el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
				</el-form-item> -->
				<el-form-item label="轮播图图片" prop="url">
					<ImageUpload v-model="form.url" limit="1" />
					<!-- <el-input v-model="form.url" placeholder="请输入图片地址或上传" /> -->
					<!-- 实际项目中这里会用一个图片上传组件 -->
				</el-form-item>
				<!-- <el-form-item label="状态">
					<el-radio-group v-model="form.status">
						<el-radio :label="0">启用</el-radio>
						<el-radio :label="1">禁用</el-radio>
					</el-radio-group>
				</el-form-item> -->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { listCarousel, getCarousel, addCarousel, updateCarousel, delCarousel } from '@/api/carousel';
// import ImageUpload from '@/components/ImageUpload'; // 假设有这个组件

export default {
	name: 'CarouselManagement',
	// components: { ImageUpload },
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 轮播图表格数据
			carouselList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				title: undefined,
				status: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				title: [{ required: true, message: '轮播图标题不能为空', trigger: 'blur' }],
				url: [{ required: true, message: '轮播图图片不能为空', trigger: 'blur' }],
				sortOrder: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
			}
		};
	},
	created() {
		this.getList();
	},
	methods: {
		/** 查询轮播图列表 */
		getList() {
			this.loading = true;
			listCarousel(this.queryParams)
				.then(response => {
					response.rows.forEach(item => {
						item.url = process.env.VUE_APP_BASE_API + item.url;
					});
					this.carouselList = response.rows;
					this.total = response.total;
					this.loading = false;
				})
				.catch(() => {
					this.loading = false;
				});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				title: undefined,
				url: undefined,
				linkUrl: undefined,
				sortOrder: 0,
				status: 0 // 默认启用
			};
			this.resetForm('form');
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm('queryForm'); // 如果有queryForm的话
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = '添加轮播图';
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const id = row.id || this.ids[0];
			getCarousel(id).then(response => {
				this.form = response.data;
				this.open = true;
				this.title = '修改轮播图';
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs['form'].validate(valid => {
				if (valid) {
					if (this.form.id != null) {
						updateCarousel(this.form).then(response => {
							this.$message.success('修改成功');
							this.open = false;
							this.getList();
						});
					} else {
						addCarousel(this.form).then(response => {
							this.$message.success('新增成功');
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids;
			this.$confirm('是否确认删除轮播图编号为"' + ids + '"的数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(function () {
					return delCarousel(ids);
				})
				.then(() => {
					this.getList();
					this.$message.success('删除成功');
				})
				.catch(() => {});
		},
		// 用户状态修改
		handleStatusChange(row) {
			let text = row.status === 0 ? '启用' : '禁用';
			this.$confirm('确认要"' + text + '""' + row.title + '"轮播图吗?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(function () {
					return updateCarousel({ id: row.id, status: row.status });
				})
				.then(() => {
					this.$message.success(text + '成功');
				})
				.catch(function () {
					row.status = row.status === 0 ? 1 : 0;
				});
		},
		// parseTime 方法 (如果项目中没有全局混入)
		parseTime(time, pattern) {
			if (arguments.length === 0 || !time) {
				return null;
			}
			const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
			let date;
			if (typeof time === 'object') {
				date = time;
			} else {
				if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
					time = parseInt(time);
				} else if (typeof time === 'string') {
					time = time.replace(new RegExp(/-/gm), '/');
				}
				if (typeof time === 'number' && time.toString().length === 10) {
					time = time * 1000;
				}
				date = new Date(time);
			}
			const formatObj = {
				y: date.getFullYear(),
				m: date.getMonth() + 1,
				d: date.getDate(),
				h: date.getHours(),
				i: date.getMinutes(),
				s: date.getSeconds(),
				a: date.getDay()
			};
			const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
				let value = formatObj[key];
				if (key === 'a') {
					return ['日', '一', '二', '三', '四', '五', '六'][value];
				}
				if (result.length > 0 && value < 10) {
					value = '0' + value;
				}
				return value || 0;
			});
			return time_str;
		},
		// resetForm (如果项目中没有全局混入)
		resetForm(refName) {
			if (this.$refs[refName]) {
				this.$refs[refName].resetFields();
			}
		}
	}
};
</script>

<style scoped>
.app-container {
	padding: 20px;
}
.mb8 {
	margin-bottom: 10px;
}
</style>
